#include "thread.h"
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <sys/time.h>

static void * threadfunc(void * arg)
{
  char *name = arg;
  printf("je suis le thread %p, lancé avec l'argument %s\n",
	 thread_self(), name);
  thread_yield();
  printf("je suis encore le thread %p, lancé avec l'argument %s\n",
	 thread_self(), name);
	 
	 int i = 50; int j;
	 struct timeval tv, tvi;
	 
	 while(i>0) {
	    printf("%p : %d\n", thread_self(), i--);
	    gettimeofday(&tvi, NULL);
	    do {
	      j++;
	      gettimeofday(&tv, NULL);
	      j--;
	      } while(tv.tv_sec*1000000 - tvi.tv_sec*1000000 + tv.tv_usec - tvi.tv_usec<100000);
	 }
	 
  thread_exit(arg);
}

int main(int argc, char *argv[])
{
  thread_t thread1, thread2, thread3;
  void *retval1, *retval2, *retval3;
  int err;

  printf("le main lance 3 threads...\n");
  err = thread_create(&thread1, threadfunc, "thread1");
  assert(!err);
  err = thread_create(&thread2, threadfunc, "thread2");
  assert(!err);
  err = thread_create(&thread3, threadfunc, "thread3");
  assert(!err);
  printf("le main a lancé les threads %p, %p et %p\n",
	 thread1, thread2, thread3);

  printf("le main attend les threads\n");
  err = thread_join(thread2, &retval2);
  assert(!err);
  err = thread_join(thread1, &retval1);
  assert(!err);
  err = thread_join(thread3, &retval3);
  assert(!err);
  printf("les threads ont terminé en renvoyant '%s' and '%s' and '%s'\n",
	 (char *) retval1, (char *) retval2, (char *) retval3);
	

   

  return 0;
}
